package com.fc.v2.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.fc.v2.common.conf.V2Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;

@Component
public class QrCodeUtils {

    @Autowired
    private V2Config config;


    private String relativePathPrefix;

    private  String absolutePathPrefix;

    private  String customPathEnable;

    private static final Logger log = LoggerFactory.getLogger(QrCodeUtils.class);


    private static RandomStringFactory factory = new FileNameFactory();

    /**存储二维码的文件夹*/
    private static String storedFolder = "qrCode";

    public static String getStoredFolder() {
        return storedFolder;
    }

    public static void setStoredFolder(String storedFolder) {
        QrCodeUtils.storedFolder = storedFolder;
    }

    public static void setFactory(RandomStringFactory f) {
        factory = f;
    }

    /**
     * 生成二维码
     * @param msg
     * @return 返回文件名称
     */
    public String generate(String msg){
        return generate(msg,storedFolder);
    }

    /**
     * 生成二维码
     * @param msg
     * @param storedFolder qrcode
     * @return 返回文件名称
     */
    public String generate(String msg,String storedFolder){

     relativePathPrefix =config.getRelativePath();

     absolutePathPrefix =config.getAbsolutePath();

     customPathEnable=config.getCustomPathEnable();


        String filePath = "";
        String fileName = factory.getString() + ".jpg";

        /** /qrCode/123123.jpg */
        String relativePath = "/" + storedFolder + "/" + fileName;


        if("Y".equals(customPathEnable)){
            filePath = absolutePathPrefix + relativePath;
        }else{
            filePath = relativePathPrefix + relativePath;
        }

        //创造父路径
        File file = new File(filePath).getParentFile();
        if(!file.exists()){
            file.mkdirs();
        }


        log.debug("二维码保存路径：{}",filePath);

        // 生成二维码到文件
        QrCodeUtil.generate(msg, 300,300, FileUtil.file(filePath));
        return fileName;
    }

}
